package com.mindata.blockchain.core.service.LogMessage;

import com.mindata.blockchain.block.*;
import com.mindata.blockchain.block.LogMessage.IMessageService;

import com.mindata.blockchain.block.LogMessage.LogMessageEntity;
import com.mindata.blockchain.core.manager.DbBlockManager;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
public class LogMessageService implements IMessageService<LogMessageEntity> {
    @Resource
    private DbBlockManager dbBlockManager;


    @Override
    public List<LogMessageEntity> getMessage(String instructionId) {

        Block block=dbBlockManager.getFirstBlock();
        LogMessageEntity logMessage = new LogMessageEntity();
        List<LogMessageEntity> logMessageList = new LinkedList();
        String str ="";

        do{
            List<Instruction> instructions = block.getBlockBody().getInstructions();
            for(Instruction i : instructions) {
                if (i.getInstructionId().equals(instructionId)) {
                    logMessage.setInstructionId(instructionId);
                    logMessage.setNumber(block.getBlockHeader().getNumber());
                    logMessage.setTimeStamp(i.getTimeStamp());
                    logMessage.setOperation(i.getOperation());
                    logMessage.setTable(i.getTable());
                    logMessage.setOldJson(i.getOldJson());
                    logMessage.setJson(i.getJson());
                    logMessageList.add(logMessage);
                }
            }
            block = dbBlockManager.getNextBlock(block);

        }while(block!=null);

        for(LogMessageEntity logMessage1 : logMessageList){
            str = str + logMessage1;
        }

        return logMessageList;
    }
}
